<template>
  <el-form
    :model="formData"
    :rules="rules"
    ref="formRef"
    label-width="100px"
    class="form-container"
  >
    <el-form-item label="专辑名称" prop="title">
      <el-input v-model="formData.title" placeholder="请输入专辑名称"></el-input>
    </el-form-item>
    <el-form-item label="分类" prop="classId">
      <el-select placeholder="请选择分类" v-model="formData.classId">
        <el-option
          v-for="item in categoryNames"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="专辑描述" prop="description">
      <el-input
        v-model="formData.description"
        type="textarea"
        placeholder="请输入专辑描述"
        show-word-limit  maxlength="500"
      ></el-input>
    </el-form-item>
    <el-form-item label="专辑封面" prop="cover">
      <ImageUpload v-model:fileList="formData.fileList" ref="imageUploadRef" />
    </el-form-item>
  </el-form>
  <view class="button-container">
    <el-button type="primary" @click="submitForm">提交</el-button>
    <el-button @click="resetForm">重置</el-button>
  </view>
</template>

<script setup>
import { reactive, ref, watch } from 'vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { apiGetCategoryNames } from '@/api/wallpaper/classify'
import {  apiPostingAlbum } from '@/api/wallpaper/posting'
import useUserStore from '@/store/modules/user'

const formData = reactive({
  title: '',
  description: '',
  cover: [],
})

const rules = reactive({
  title: [{ required: true, message: '请输入专辑名称', trigger: 'blur' }],
  // cover: [{ required: true, message: '请上传封面', trigger: 'change' }],
})

const formRef = ref(null)

const imageUploadRef = ref(null)
const album = ref(null)
const userStore = useUserStore()

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await imageUploadRef.value.submitUpload()
      watch(
        () => formData.fileList,
        (newVal) => {
          if (newVal.length && newVal.length > 0) {
            // 更新 album.value，只包含必要的属性
            album.value = {
              imgUrl: newVal[0].url,
              ...pick(formData, ['description', 'title', 'classId']), // pick 函数用于选择特定的属性
            }
            album.value.userId = userStore.id
            album.value.nickname = userStore.name
            console.log(album.value)
            // 调用 api 上传壁纸
            apiPostingAlbum(album.value)
              .then((res) => {
                // console.log(res)
                if (res.code === 200) {
                  // 上传成功，重置表单
                  resetForm()
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            // 如果 fileList 变为空，重置 album.value
            album.value = null
          }
        },
        { deep: true, immediate: true }, // 立即执行一次监听器以处理初始值
      )
    } else {
      console.log('error submit', formData)
      return false
    }
  })
}

// 辅助函数 pick，用于从对象中提取指定的属性
function pick(obj, keys) {
  return keys.reduce((acc, key) => {
    if (obj && Object.prototype.hasOwnProperty.call(obj, key)) {
      acc[key] = obj[key]
    }
    return acc
  }, {})
}
const resetForm = () => {
  formRef.value.resetFields()
  imageUploadRef.value.resetUpload()
}

const categoryNames = ref([])

// 获取分类名称
apiGetCategoryNames('2').then((res) => {
  categoryNames.value = res.data
})
</script>

<style lang="scss" scoped>
.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.button-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 800px;

  .el-button {
    flex-grow: 1;
    margin: 0 5px;
  }
}
</style>
